#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2021/12/20 17:23
    Desc  :
--------------------------------------
"""
import datetime
import random
import string
import time

from django.core.cache import cache

from common.utils.log_utils import logger
from platform_auth.settings import JWT_EXPIRATION_DELTA, EXPIRE_TIMEOUT


class AccessTokenUtil():

    def __init__(self):
        self.size = 6
        self.expire = JWT_EXPIRATION_DELTA
        self.expire_int = int(time.mktime(self.expire.timetuple()))

    def generate_token(self):
        token = f"{''.join(random.choice(string.ascii_uppercase) for _ in range(self.size))}-{self.expire_int}"
        return token

    @staticmethod
    def verify_token(token: str):
        return cache.get(token)

    @staticmethod
    def save_token(token: str, userInfo: dict, timeout=EXPIRE_TIMEOUT):
        cache.set(
            key = token,
            value = userInfo,
            timeout = timeout
        )


class RequestAuthTokenUtil(AccessTokenUtil):

    def __init__(self, request):
        super().__init__()
        self.request = request
        self.token = request.headers.copy().get('Accesstoken')

    def get_user_id_and_username(self):
        data = cache.get(self.token)
        if data:
            return data.get('id'), data.get('realName')

        return None, None

    def get_user_id(self):
        data = cache.get(self.token)
        if data:
            return data.get('id')
        return None

    def delete_token(self):
        cache.delete(self.token)

    def get_project(self):
        return self.request.headers.copy().get('Project')

    def get_token_into(self):
        data = cache.get(self.token)
        if data:
            return data
        return {}
